package com.example.user.viewmodel

import androidx.lifecycle.viewModelScope
import com.example.mvi_core.model.model.BaseViewModel
import com.example.user.entity.UserEntity
import com.example.user.intent.UserIntent
import com.example.user.model.UserModel
import com.example.user.state.UserState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class UserViewModel:BaseViewModel<UserIntent,UserState>() {
    private val model by lazy{UserModel()}
    private val mutableState=MutableStateFlow<UserState>(UserState.Loading)
    val observeState:StateFlow<UserState>
    get() = mutableState
    init {
        viewModelScope.launch {
            channel.consumeAsFlow().collect {
                when(it){
                    is UserIntent.Register ->{
                        val register = model.register(it.password, it.name)
                        if(register.code==0){
                            mutableState.value=UserState.Success(register.data)
                        }else{
                            mutableState.value=UserState.Failure(register.msg)
                        }
                    }
                    is UserIntent.Login ->{
                        val login = model.login(it.password, it.name)
                        if(login.code==0){
                            mutableState.value=UserState.Success(login.data)
                        }else{
                            mutableState.value=UserState.Failure(login.msg)
                        }
                    }

                }
            }
        }
    }
}